package icu.wdtt.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import icu.wdtt.Utils.EmailSendUtils;
import icu.wdtt.Utils.RandomCodeUtils;
import icu.wdtt.Utils.ResultUtils;
import icu.wdtt.enumModel.HttpRequestMessage;
import icu.wdtt.exception.UserException;
import icu.wdtt.model.FileBase64;
import icu.wdtt.model.Result;
import icu.wdtt.model.User;
import icu.wdtt.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("user")
@Api( "包含增删改查，以及登陆丶注销丶注册等功能,部分功能需要管理员权限")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ResultUtils resultUtils;
    @Autowired
    private EmailSendUtils emailSendUtils;

    @ApiOperation(value = "后台添加用户" , notes = "需要管理员权限")
    @PostMapping("add")
    public Result add(String username , @RequestParam(defaultValue = "a123456") String password,String email, String roleName) throws Exception {
        Boolean flag = userService.setUser(username, password, email, roleName);
        if(flag){
                return resultUtils.success(HttpRequestMessage.SUCCESS_ADD);
            }
        return resultUtils.fail(HttpRequestMessage.FAIL_ADD);
    }
    @ApiOperation(value = "查询所有用户" , notes = "需要管理员权限")
    @GetMapping("getAll")
    public Result getAll() throws Exception{
            List<User> userList = userService.getAll();
            if(userList != null){
                return resultUtils.success(HttpRequestMessage.SUCCESS_QUERY,userList,userList.size());
            }
            return resultUtils.fail(HttpRequestMessage.FAIL_QUERY);
    }
    @ApiOperation(value = "查询指定用户" , notes = "需要管理员权限")
    @GetMapping(path = "get",params = "id")
    public Result get(int id) throws Exception{
        try {
            User user = userService.get(id);
            if(user !=null){
                return resultUtils.success(HttpRequestMessage.SUCCESS_QUERY,user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtils.fail(HttpRequestMessage.FAIL_QUERY);
    }
    @ApiOperation(value = "修改用户信息" , notes = "需要管理员权限")
    @PostMapping("update")
    public Result update(User user) throws Exception{
        try {
            Boolean update = userService.update(user);
            if(update){
                return resultUtils.success(HttpRequestMessage.SUCCESS_UPDATE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtils.fail(HttpRequestMessage.FAIL_UPDATE);
    }
    @ApiOperation(value = "删除用户" , notes = "需要管理员权限")
    @PostMapping(path = "del",params = "id")
    public Result del(int id) throws Exception{
        try {
            Boolean del = userService.del(id);
            if(del){
                return resultUtils.success(HttpRequestMessage.SUCCESS_DELETE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtils.fail(HttpRequestMessage.SUCCESS_DELETE);
    }

    @ApiOperation(value = "登陆方法",notes = "登陆之后请访问user/main接口获取当前登陆用户信息")
    @PostMapping(path = "login",params = {"username","password"})
    public Result login(String username, String password ) throws Exception {

        if (StpUtil.isLogin()) {
            return resultUtils.fail("已登陆,请注销之后在登陆!", 400);
        }
            User userLogin = userService.login(username, password);
            if (userLogin != null) {
                //将登陆用户的ID放入sa-token中
                StpUtil.login(userLogin.getUid());
                //将登陆用户的信息放入sa-token中
                StpUtil.getSession().set("user", userLogin);
                return resultUtils.success(HttpRequestMessage.SUCCESS_LOGIN);
            }

            return resultUtils.fail(HttpRequestMessage.FAIL_LOGIN);
        }

    @GetMapping(path = "getPage",params = {"pageNum","pageSize"})
    public Result getPage(int pageNum,int pageSize) throws Exception{

            List<User> userListPage = userService.getPage(pageNum, pageSize);
            if(userListPage != null){
                return resultUtils.success(HttpRequestMessage.SUCCESS_QUERY,userListPage,userListPage.size());
            }
        return resultUtils.fail(HttpRequestMessage.FAIL_QUERY);
    }

    @ApiOperation(value = "获取当前用户信息方法",notes = "一般用于登陆之后请求")
    @GetMapping("main")
    public Result main() throws Exception{

            User user = StpUtil.getSession().getModel("user",User.class);
            if(user !=null){
                return resultUtils.success(HttpRequestMessage.SUCCESS_QUERY,user);
            }

        return resultUtils.fail(HttpRequestMessage.FAIL_QUERY);
    }

    @ApiOperation(value = "注册方法",notes = "注册表单里需要对邮箱进行验证;访问user/email接口来发送邮箱" +
            "访问user/isEmail接口来验证邮箱验证码是否正确;这个验证暂时仅限于前端表单里的限制，实际访问这个接口只用带上邮箱即可，" +
            "不需要带上邮箱验证码;"+"需要携带token(checkId)")
    @PostMapping(path = "register",params = {"username","password","email","checkCode","checkId"})
    public Result register(String username , String password,String email) throws Exception{

            Boolean flag = userService.register(username, password,email);
            if(flag){
                return resultUtils.success(HttpRequestMessage.SUCCESS_REGISTER);
            }
        return resultUtils.fail(HttpRequestMessage.FAIL_REGISTER);
    }

    @ApiOperation(value = "注销方法",notes = "当前用户退出")
    @GetMapping("quit")
    public Result quit() throws Exception{
            //注销会话
            StpUtil.logout();
            return resultUtils.success("注销成功!",200);
    }

    @ApiOperation(value = "获取验证码",notes = "访问直接获取验证码图片,验证码图片将以base64的方式返回" +
            "并在返回的信息里含有checkId的值")
    @GetMapping("checkCode")
    public Result checkCode(HttpServletResponse response) throws Exception{
        try{
            FileBase64 imageBase64 = RandomCodeUtils.createRandomCode(response);
            if(imageBase64 != null){
                return resultUtils.success(HttpRequestMessage.SUCCESS_GET_CODE,imageBase64);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultUtils.fail(HttpRequestMessage.FAIL_GET_CODE);
    }

    @ApiOperation(value = "验证用户名是否被使用",notes = "一般用于的表单的动态验证")
    @GetMapping(path = "isUserName",params = "username")
    public Result isUserName(String username) throws Exception{
            Boolean flag = userService.isUserName(username);
            if(flag){
                return resultUtils.success(HttpRequestMessage.SUCCESS_IS_USERNAME);
            }
        return resultUtils.fail(HttpRequestMessage.FAIL_IS_USERNAME);
    }

    @ApiOperation(value = "发送邮件",notes = "一般在用户点击“发送”按钮之后访问发送邮件,请将响应体中的emailId获取，" +
            "并在需要验证邮箱验证码的接口的请求体中设置emailId")
    @GetMapping(path = "email",params = {"email"})
    public Result email(String email) throws Exception {
        FileBase64 emailToken = emailSendUtils.send(email);
        if (emailToken != null) {
            return resultUtils.success("邮件发送成功!", 200, emailToken);
        }
        return resultUtils.fail("邮件发送失败!", 400);
    }

    @ApiOperation(value = "检验邮件验证码",notes = "请求体中请携带emailId!")
    @GetMapping(path = "isEmail",params = {"emailCode","emailId"})
    public Result isEmail(String emailCode,String emailId) throws Exception{

            Boolean flag = userService.isEmail(emailCode,emailId);
            if(flag){
                return resultUtils.success(HttpRequestMessage.SUCCESS_CHECK_CODE);
            }

        return resultUtils.fail(HttpRequestMessage.FAIL_CHECK_CODE);
    }


    @ApiOperation(value = "重置密码,根据邮箱",notes = "这里需要将用户输入的邮箱验证码携带，并且需要携带emailId")
    @PostMapping(path = "retPassword" , params = {"username","emailCode","password","email","emailId"})
    public Result retPassword(String username ,String email,String emailCode,String password,String emailId) throws Exception{

        Boolean flag = userService.retPassword(username, email, emailCode, password, emailId);
        if(flag){
                return resultUtils.success(HttpRequestMessage.SUCCESS_RESET);
        }
        return resultUtils.fail(HttpRequestMessage.FAIL_RESET);
    }


    @ApiOperation(value = "重置密码，根据旧密码" , notes = "用户登陆之后才可用")
    @PostMapping(path = "updatePassword",params = {"oldPassword","newPassword"})
    public Result updatePassword(String oldPassword , String newPassword) throws Exception{

            Boolean flag = userService.updatePassword(StpUtil.getLoginIdAsInt(), oldPassword, newPassword);
            if(flag){
                return resultUtils.success(HttpRequestMessage.SUCCESS_UPDATE);
            }

        return resultUtils.fail(HttpRequestMessage.FAIL_UPDATE);
    }

    @ApiOperation(value = "查询所有用户,携带角色信息" , notes = "需要管理员权限,默认开启分页")
    @GetMapping("getUserAndRoleAll")
    public Result getUserAndRoleAll(@RequestParam(defaultValue = "1") int pageNum ,
                                    @RequestParam(defaultValue = "10")int pageSize){
        //开启分页查询
        PageHelper.startPage(pageNum,pageSize);
        List<User> userAndRoleAll = userService.getUserAndRoleAll();
        //获取PageInfo对象来获取查询总数
        PageInfo<User> pageResult = new PageInfo<User>(userAndRoleAll);
        if(userAndRoleAll != null){
            return resultUtils.success(HttpRequestMessage.SUCCESS_QUERY,userAndRoleAll,(int)pageResult.getTotal());
        }
        return resultUtils.fail(HttpRequestMessage.FAIL_QUERY);
    }
    @ApiOperation(value = "查询指定用户,携带角色信息" , notes = "需要管理员权限")
    @GetMapping("getUserAndRoleByUid")
    public Result getUserAndRoleByUid(){
        User user = userService.getUserAndRoleByUid(StpUtil.getLoginIdAsInt());
        if(user != null){
            return resultUtils.success(HttpRequestMessage.SUCCESS_QUERY,user);
        }
        return resultUtils.fail(HttpRequestMessage.FAIL_QUERY);
    }
    @ApiOperation(value = "查询所有用户,携带文件信息" , notes = "需要管理员权限,默认开启分页")
    @GetMapping("getUserAndFilesAll")
    public Result getUserAndFilesAll(@RequestParam(defaultValue = "1") int pageNum ,
                                     @RequestParam(defaultValue = "10")int pageSize){
        //开启分页查询
        PageHelper.startPage(pageNum,pageSize);
        List<User> userAndFilesAll = userService.getUserAndFilesAll();
        //获取PageInfo对象来获取查询总数
        PageInfo<User> pageResult = new PageInfo<User>(userAndFilesAll);
        if(userAndFilesAll != null){
            return resultUtils.success(HttpRequestMessage.SUCCESS_QUERY,userAndFilesAll,(int)pageResult.getTotal());
        }
        return resultUtils.fail(HttpRequestMessage.FAIL_QUERY);
    }
    @ApiOperation(value = "查询指定用户,携带文件信息" , notes = "需要管理员权限")
    @GetMapping("getUserAndFilesByUid")
    public Result getUserAndFilesByUid(){
        User user = userService.getUserAndFilesByUid(StpUtil.getLoginIdAsInt());
        if(user != null){
            return resultUtils.success(HttpRequestMessage.SUCCESS_QUERY,user);
        }
        return resultUtils.fail(HttpRequestMessage.FAIL_QUERY);
    }


}
